﻿/* Module           Welcome Screen 
 * purpose          show help Topics in tabluar and list views
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Apps;
using System.IO;
using System.Windows.Media.Imaging;
using VAdvantage.Utility;
using System.Collections.ObjectModel;
using System.Data;
using VAdvantage.Model;
using System.Runtime.InteropServices.Automation;
using System.Text;
using System.Windows.Browser;
using SilverlightDesktop.Controls;

namespace VAdvantage.KnowledgeBase
{
    public partial class WelcomeScreen : UserControl, FormPanel
    {
        #region Decaration

        /* double click handler */
        private SilverlightDesktop.Common.DoubleClickHelper helper;
        private SilverlightDesktop.Common.DoubleClickHelper helperAction;

        /* parent frame */
        private FormFrame _frame = null;
        /* context */
        Ctx _ctx = Envs.GetCtx();
        /* language login  */
        String langCode = "en_US";
        /* browser url */
        private String appURL = "";

        /*Parent Form directly invoke form class*/

        private Form _parentForm = null;
        #endregion

        #region "Constructor"
       
        /// <summary>
        /// Default const must[Reflection]
        /// </summary>
        public WelcomeScreen()
        {
            // InitializeComponent();
        }
        
        #endregion
     
        #region FormPanel Members

        /// <summary>
        /// FormPanel interface funcion , initilize user control
        /// </summary>
        /// <param name="windowNo">current win number</param>
        /// <param name="frame">parent frame</param>
        public void Init(int windowNo, FormFrame frame)
        {
            InitializeComponent();

            appURL = Envs.GetApplicationURL();

            langCode = Utility.Envs.GetAD_Language(_ctx);

            Init();
            
            _frame = frame;

            // ShowInTaskBar="False" ResizeMode="NoResize" FormBorderColor="#b7c8d3" FormBorderThickness="0"
            _frame.FormStyle = SilverlightDesktop.Common.FormStyle.None;
            _frame.ShowInTaskBar = false;
            _frame.ResizeMode = SilverlightDesktop.Common.ResizeMode.NoResize;
            _frame.FormBorderThickness = new Thickness(0);
            _frame.FormBorderColor = Envs.GetColorFromHexString("B7C8D3");

            _frame.ContentGrid.Children.Add(this);
            Envs.ShowForm(_frame);
        }

        public void Dispose()
        {
            _frame = null;
            _parentForm = null;
        }


       /// <summary>
       /// invoke when call from direct class [ShortCut]
       /// </summary>
       /// <param name="welcomePage"></param>
        internal void Init(Form welcomePage)
        {
            _parentForm = welcomePage;
            InitializeComponent();

            appURL = Envs.GetApplicationURL();

            langCode = Utility.Envs.GetAD_Language(_ctx);

            Init();
        }


        #endregion

        #region Function

        /// <summary>
        /// Initilize Data Request & set user control text 
        /// </summary>
        private void Init()
        {
            GetData("","");

            GetDataInitConfig("", "");

            Ctx _ctx = Envs.GetCtx();
            chkWelcome.Content = Msg.GetMsg("DontShowScreen");
            btnFirst.Text = Msg.GetMsg("First");
            btnLast.Text = Msg.GetMsg("Last");
            btnClose.Text = Msg.GetMsg("Close");
            btnClose2.Text = Msg.GetMsg("Close");
            txtGoto.Tag = Msg.GetMsg("Goto");

            chkNews.Content = Msg.GetMsg("News");
            chkTopic.Content = Msg.GetMsg("Topic");

            chkInitConfig.Content = Msg.GetMsg("InitConfig");

            btnClose.Icon = Envs.LoadImageSource("cancel.png");
            btnClose2.Icon = Envs.LoadImageSource("cancel.png");
            btnFirst.Icon = Envs.LoadImageSource("arrow-up-Trans.png");
            btnLast.Icon = Envs.LoadImageSource("arrow-down.png");

            chkInitConfig.IsChecked = true;

            //SetWelComeStatus();

           // chkWelcome.Checked += new RoutedEventHandler(chkWelcome_Checked);
           // chkWelcome.Unchecked += new RoutedEventHandler(chkWelcome_Unchecked);

        }

        /// <summary>
        /// set user choice [show welcome screen]
        /// </summary>
        private void SetWelComeStatus()
        {
           chkWelcome.IsChecked = DataBase.Ini.IsHideWelcomeScreen();
        }

        /// <summary>
        /// Checked changed event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void chkWelcome_Checked(object sender, RoutedEventArgs e)
        {
            DataBase.Ini.SetProperty(DataBase.Ini.P_WELCOME_SCREEN, chkWelcome.IsChecked.Value?"Y": "N");
        }
        /// <summary>
        /// Unchecked event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void chkWelcome_Unchecked(object sender, RoutedEventArgs e)
        {
            DataBase.Ini.SetProperty(DataBase.Ini.P_WELCOME_SCREEN, chkWelcome.IsChecked.Value ? "Y" : "N");
        }

        /// <summary>
        /// init get data Request
        /// </summary>
        /// <param name="serachText"></param>
        /// <param name="option"></param>
        private void GetData(string serachText, string option)
        {
            SetBusyTopic(true);
            stTabular.Children.Clear();
            var clientTopic = Utility.AEnv.GetDataServiceBasicClient();

            clientTopic.GetTopicInfoCompleted += new EventHandler<DataServiceBasic.GetTopicInfoCompletedEventArgs>(clientTopic_GetTopicInfoCompleted);
            clientTopic.GetTopicInfoAsync(appURL, false,langCode,serachText,"");
            clientTopic.CloseAsync();
        }

        /// <summary>
        /// Service complete event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void clientTopic_GetTopicInfoCompleted(object sender, DataServiceBasic.GetTopicInfoCompletedEventArgs e)
        {
            if (e.Error != null || e.serviceError != null)
            {
                SetBusyTopic(false);
                Logging.VLogger.Get().Severe(e.serviceError);
                //Classes.ShowMessage.Error("Error?", true, e.serviceError);
                return;
            }

            if (String.IsNullOrEmpty(e.Result))
            {
                SetBusyTopic(false);
                return;
            }
            ////InitilizeList
            //if (lstSearch == null)
            //{
            //    lstSearch = new List<KeyNamePair>();
            //    lstSearch.Add(new KeyNamePair(-1, " "));
            //}

            IDataReader dr = new DataReader();
            dr.SetData(e.Result);

            String name = "", desc = "", help = "";
            int id = 0, fkId = 0;

            BitmapSource img = null;
            Byte[] bArr = null;
            Object array = "";
            ObservableCollection<TopicInfo> list = new ObservableCollection<TopicInfo>();
            ImageTextControl ctrl = null;

            while (dr.Read())
            {
                name = dr["Name"].ToString();
                desc = dr["Description"].ToString();
                help = dr["Help"].ToString();
                array = dr["BinaryData"];
                if (array != null && array is byte[])
                {
                    MemoryStream ms = new MemoryStream((byte[])array);
                    img = new BitmapImage();
                    img.SetSource(ms);
                }

                id = Utility.Util.GetValueOfInt(dr["K_TopicInfo_ID"]);

                list.Add(new TopicInfo(id, name, desc, help, array));
                ctrl = new ImageTextControl(img, name, id);
                ctrl.Width = 150;
                ctrl.Height = 125;
                //ctrl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                ctrl.Margin = new Thickness(1, 1, 10, 10);
                ctrl.Click += new EventHandler<MouseButtonEventArgs>(ctrl_Click);
                //ctrl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                stTabular.Children.Add(ctrl);

               // lstSearch.Add(new KeyNamePair(id, name));
            }

            lstGrid.ItemsSource = list;

            SetBusyTopic(false);
            
        }

        /// <summary>
        /// Get data [Topics]
        /// </summary>
        /// <param name="serachText"></param>
        /// <param name="option"></param>
        private void GetDataInitConfig(string serachText, string option)
        {
            SetBusyInit(true);
            stInitTabular.Children.Clear();
            var clientInitConfig = Utility.AEnv.GetDataServiceBasicClient();
            clientInitConfig.GetTopicInfoCompleted += new EventHandler<DataServiceBasic.GetTopicInfoCompletedEventArgs>(clientInitConfig_GetTopicInfoCompleted);
            clientInitConfig.GetTopicInfoAsync(appURL, true, langCode, serachText, "");
            clientInitConfig.CloseAsync();
        }

        void clientInitConfig_GetTopicInfoCompleted(object sender, DataServiceBasic.GetTopicInfoCompletedEventArgs e)
        {
           
            if (e.Error != null || e.serviceError != null)
            {
                SetBusyInit(false);
                Logging.VLogger.Get().Severe(e.serviceError);
                //Classes.ShowMessage.Error("Error?", true, e.serviceError);
                return;
            }

            if (String.IsNullOrEmpty(e.Result))
            {
                SetBusyInit(false);
                return;
            }


            IDataReader dr = new DataReader();
            dr.SetData(e.Result);

            String name = "", desc = "", help = "";
            int id = 0, fkId = 0;

            BitmapSource img = null;
            Byte[] bArr = null;
            Object array = "";
            ObservableCollection<TopicInfo> list = new ObservableCollection<TopicInfo>();
            ImageTextControl ctrl = null;

            while (dr.Read())
            {
                name = dr["Name"].ToString();
                desc = dr["Description"].ToString();
                help = dr["Help"].ToString();
                array = dr["BinaryData"];
                if (array != null && array is byte[])
                {
                    MemoryStream ms = new MemoryStream((byte[])array);
                    img = new BitmapImage();
                    img.SetSource(ms);
                }

                id = Utility.Util.GetValueOfInt(dr["K_TopicInfo_ID"]);

                list.Add(new TopicInfo(id, name, desc, help, array));
                ctrl = new ImageTextControl(img, name, id);
                ctrl.Width = 150;
                ctrl.Height = 125;
                //ctrl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                ctrl.Margin = new Thickness(1, 1, 10, 10);
                ctrl.Click += new EventHandler<MouseButtonEventArgs>(ctrl_Click);
                //ctrl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                stInitTabular.Children.Add(ctrl);


                //lstInitGrid.Add(new KeyNamePair(id, name));
            }
            img = null;

            lstInitGrid.ItemsSource = list;
            SetBusyInit(false);
        }

       
        /// <summary>
        /// Tablular control click event 
        /// Get Step info
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ctrl_Click(object sender, MouseButtonEventArgs e)
        {
            int id = ((ImageTextControl)sender).ID;
            GetRecord2(id);
            ShowSecondTab(true);
        }

        /// <summary>
        /// Change view image click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SwitchLayout();
        }

        /// <summary>
        /// Switch layout [Tabular or list]
        /// </summary>
        private void SwitchLayout()
        {
            //isSingle = !isSingle;


            if (chkInitConfig.IsChecked.Value)
            {
               // tabInitConfig.Visibility = System.Windows.Visibility.Visible;
                grdInitDetail.Visibility = grdInitDetail.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                grdInitTabular.Visibility = grdInitDetail.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
            }
            else if (chkTopic.IsChecked.Value)
            {
                grdDetail.Visibility = grdDetail.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                grdTabular.Visibility = grdTabular.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
            }
            else if (chkNews.IsChecked.Value)
            {
                //grdDetail.Visibility = grdInitDetail.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;

            }
            //if (isSingle)
            //{
            //    grdTabular.Visibility = System.Windows.Visibility.Collapsed;
            //    grdDetail.Visibility = System.Windows.Visibility.Visible;
            //}
            //else
            //{
            //    grdDetail.Visibility = System.Windows.Visibility.Collapsed;
            //    grdTabular.Visibility = System.Windows.Visibility.Visible;
            //}
        }

        /// <summary>
        /// Show Step Panel
        /// </summary>
        /// <param name="visible"></param>
        private void ShowSecondTab(bool visible)
        {
            grdStep.Visibility = visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            grdTopic.Visibility = visible ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
        }

        //Set busy indicator
        private void SetBusyTopic(bool isBusy)
        {
            busyIndicatorTopic.IsBusy = isBusy;

        }
        private void SetBusyInit(bool isBusy)
        {
            busyIndicatorInit.IsBusy = isBusy;

        }
        private void SetBusyStep(bool isBusy)
        {
            busyIndicatorStep.IsBusy = isBusy;

        }
        

        /// <summary>
        /// Search Topic against text
        /// </summary>
        private void Cmd_Search()
        {
            //if (txtSearch.Text == "")
            //       return;

            if (tabInitConfig.Visibility == System.Windows.Visibility.Visible)
            {
                GetDataInitConfig(txtSearch.Text, "");
            }
            else
            {
                GetData(txtSearch.Text, "");
            }
        }

        #region Tab2 Function
       
        /// <summary>
        /// Get Tpoics's step Instruction data
        /// </summary>
        /// <param name="id"></param>
        private void GetRecord2(int id)
        {
            stepDetail.Clear();
            txtStepHeader.Text = ".";

           // bool isBase = Envs.IsBaseLanguage(_ctx, "AD_window");

            SetBusyStep(true);
            lstStep.ItemsSource = null;
            lstAction.ItemsSource = null;
            if (id == 0)
                return;
            var clientStep = Utility.AEnv.GetDataServiceBasicClient();

            clientStep.GetInstructionCompleted += new EventHandler<DataServiceBasic.GetInstructionCompletedEventArgs>(clientStep_GetInstructionCompleted);
            clientStep.GetInstructionAsync(id, langCode, "");
            clientStep.CloseAsync();
           
        }

        void clientStep_GetInstructionCompleted(object sender, DataServiceBasic.GetInstructionCompletedEventArgs e)
        {
            SetBusyStep(false);
            if (e.Error != null || e.serviceError != null)
            {
                Classes.ShowMessage.Error("Error?",true, e.serviceError);
                return;
            }

            if (e.Result == null || e.Result == "")
                return;

            IDataReader dr = new DataReader();
            dr.SetData(e.Result);

            String name = "", desc = "", help = "", fkName = "",vid,vlen;
            int id = 0, fkId = 0;

            BitmapSource img = null;
            Byte[] bArr = null;
            Object array = "";
            ObservableCollection<TopicInfo> list = new ObservableCollection<TopicInfo>();
            ObservableCollection<TopicInfo> listAction = new ObservableCollection<TopicInfo>();
            ImageTextControl ctrl = null;

            while (dr.Read())
            {
                name = dr["Name"].ToString();
                desc = dr["Description"].ToString();
                help = dr["Help"].ToString();
                array = dr["BinaryData"];
                vid = dr["vid"].ToString();
                vlen = dr["length"].ToString();

                if (array != null && array is byte[])
                {
                    MemoryStream ms = new MemoryStream((byte[])array);
                    img = new BitmapImage();
                    img.SetSource(ms);
                }

                id = Utility.Util.GetValueOfInt(dr["K_Instruction_ID"]);



                string action = Utility.Util.GetValueOfString(dr["Action"]);

                if (action.Length > 0)
                {
                    fkId = Utility.Util.GetValueOfInt(dr["FKID"]);
                    if (fkId > 1)
                    {
                        fkName = Utility.Util.GetValueOfString(dr["FKName"]);
                      //  listAction.Add(new TopicInfo(id, name, desc, help, array, action, fkId, fkName));
                    }
                }

                list.Add(new TopicInfo(id, name, desc, help, array, action, fkId, fkName,vid,vlen));
            }

            lstStep.ItemsSource = list;
            lstAction.ItemsSource = listAction;
            //if (list.Count > 0)
            //{
            //    lstStep.SelectedIndex = 0;
            //}

            NavigateStep(0);
            
        }

       /// <summary>
       /// load data into control [ Step]
       /// </summary>
       /// <param name="index"></param>
        private void SetStepDetailControl(int index)
        {
            if (index < 0 || lstStep.SelectedItem == null)
                return;

            TopicInfo tInfo = lstStep.SelectedItem as TopicInfo;

            stepDetail.SetParameter(tInfo);
            txtStepHeader.Text = tInfo.Name;


        }

        /// <summary>
        /// navigate betwwen Steps
        /// </summary>
        /// <param name="index"></param>
        private void NavigateStep(int index)
        {

                btnLeftArrow.IsEnabled = false;
                grdRightArrow.IsEnabled = false;
                btnLast.Enable = false;
                btnFirst.Enable = false;

                if (lstStep.Items.Count >= 1)
                {
                    btnLeftArrow.IsEnabled = true;
                    grdRightArrow.IsEnabled = true;
                    btnLast.Enable = true;
                    btnFirst.Enable = true;

                    int newIndex = index;
                    if (index != -2)
                    {
                       newIndex = lstStep.SelectedIndex;
                        newIndex += index;
                    }

                    if (newIndex <= 0)
                    {
                        btnLeftArrow.IsEnabled = false;
                        btnFirst.Enable = false;
                        newIndex = 0;
                        //newIndex = lstStep.Items.Count - 1;
                    }
                    if (newIndex >= lstStep.Items.Count - 1)
                    {
                        grdRightArrow.IsEnabled = false;
                        btnLast.Enable = false;
                        newIndex = lstStep.Items.Count - 1;
                    }

                    lstStep.SelectedIndex = newIndex;
                }
        }

        /// <summary>
        /// show window, form, Process according to step 
        /// </summary>
        /// <param name="FKID"></param>
        /// <param name="Action"></param>
        private void StartAction(int FKID, String Action)
        {
            if (FKID < 1)
            {
                MessageBox.Show("KfId");
                return;
            }
            if (Action.Equals("W"))				//	Window
            {

                StartWindow(0, FKID);
            }
            else if (Action.Equals("P") || Action.Equals("R"))	//	Process & Report
            {
                StartProcess(FKID);
            }
            else if (Action.Equals("B"))		//	Workbench
            {
                StartWindow(FKID, 0);
            }
            //                   //else if (Action.Equals("F"))		//	WorkFlow
            //                   //{
            //                   //    if (_isMenu)
            //                   //        cmd = Utility.Util.GetValueOfInt(dr["AD_Workflow_ID"]);
            //                   //    else
            //                   //        cmd = Utility.Util.GetValueOfInt(dr["Workflow_ID"]);

                //                   //    if (_host != null)
            //                   //    {
            //                   //        _host.ShowBusyIndicator = false;
            //                   //    }
            //                   //    //if (_menu != null)
            //                   //    //{
            //                   //    //    _menu.startWorkFlow(cmd);
            //                   //    //}
            //                   //}
            //                   else if (Action.Equals("T"))		//	Task
            //                   {

                //                       StartTask(FKID);
            //                   }
            else if (Action.Equals("X"))		//	Form
            {
                StartForm(FKID);
            }
            //else
            //    log.Log(Level.SEVERE, "No valid Action in ID=" + _ID);
            //}	//	for all records
        }

        /// <summary>
        /// Intilize window
        /// </summary>
        /// <param name="AD_Workbench_ID"></param>
        /// <param name="AD_Window_ID"></param>
        private void StartWindow(int AD_Workbench_ID, int AD_Window_ID)
        {


            if (Utility.Envs.ShowWindow(AD_Window_ID))
            {
                //_host.ShowBusyIndicator = false;
                return;
            }

            //SwingUtilities.invokeLater(m_updatePB);
            AWindow frame = new AWindow();
            //frame.Explorer = _host.GetExplorer;
            // frame.SetBusyIndicator(_host);
            // frame.SetTitle(_name);

            bool OK = false;
            if (AD_Workbench_ID != 0)
                OK = frame.InitWorkbench(AD_Workbench_ID);
            else
                OK = frame.InitWindow(AD_Window_ID, null);	//	No Query Value
            if (!OK)
                return;

            //SwingUtilities.invokeLater(m_updatePB);			//	2

            //if (frame != null)
            //{
            //    //frame.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            //   // frame.Show();
            //}
            frame = null;
        }

        private void StartProcess(int AD_Process_ID)
        {
            VAdvantage.Framework.ProcessDialog pd = new VAdvantage.Framework.ProcessDialog(AD_Process_ID);
            //pd.Explorer = Envs.RegisterWindowForm _host.GetExplorer;
            Envs.RegisterWindowForm(pd);
            //_host.GetProcessDialog.Visibility = System.Windows.Visibility.Visible;
            // pd.Closed += new EventHandler(pd_Closed);
            pd.Show();
        }

        private void StartForm(int AD_Form_ID)
        {

            //System.Windows.MessageBox.Show("Form Pending");
            //if (_host != null)
            //{
            //    _host.ShowBusyIndicator = false;
            //}

            if (AD_Form_ID == 115) // Tree Maintainance
            {
                // TreeMaintenance tree = new TreeMaintenance();
                // tree.Show();
                return;
            }
            if (AD_Form_ID == 117) //WorkFlowActivity
            {
                Apps.WF.WFActivity frmWfActivity = new VAdvantage.Apps.WF.WFActivity();
                Utility.Envs.RegisterWindowForm(frmWfActivity);
                frmWfActivity.Show();
                return;
            }

            if (AD_Form_ID == 102) // Initial Tenant Setup
            {
                VAdvantage.Framework.VSetup setup = new VAdvantage.Framework.VSetup();
                Utility.Envs.RegisterWindowForm(setup);
                setup.Show();
                return;
            }

            FormFrame ff = new FormFrame();
            ff.OpenForm(AD_Form_ID);
            //ff.Closing += new EventHandler<System.ComponentModel.CancelEventArgs>(ff_Closing);
            // ff.ShowDialog();
        }

        #endregion

        #endregion

        #region events

        private void btnClose2_Click(object sender, RoutedEventArgs e)
        {
            //grdStep.Visibility = System.Windows.Visibility.Collapsed;
            ShowSecondTab(false);
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            //Dialogs.YTDialog d = new Dialogs.YTDialog("qwRsBAU1h4c");
            //d.Show();
            if (_parentForm != null)
            {
                _parentForm.Close();
            }

            if (_frame != null)
            {
                _frame.Close();
                
            }
        }

        List<SilverlightDesktop.Common.DoubleClickHelper> lstHelperTopic = new List<SilverlightDesktop.Common.DoubleClickHelper>();

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {

            helper = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)sender,true);
           // helper.DoubleClick += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            helper.Click += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            ((FrameworkElement)sender).Loaded -= Grid_Loaded;
        }

        List<SilverlightDesktop.Common.DoubleClickHelper> lstHelperInit = new List<SilverlightDesktop.Common.DoubleClickHelper>();
        private void GridInit_Loaded(object sender, RoutedEventArgs e)
        {
            helper = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)sender,true);
            helper.Click += new EventHandler<MouseButtonEventArgs>(helperInit_DoubleClick);
            ((FrameworkElement)sender).Loaded -= GridInit_Loaded;
           // lstHelperInit.Add(helper);
        }

        void helper_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            int id = 0;
            if (lstGrid.SelectedItem != null)
            {
                id = ((TopicInfo)lstGrid.SelectedItem).ID;
            }
            GetRecord2(id);
            ShowSecondTab(true);
        }

        void helperInit_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            int id = 0;
            if (lstInitGrid.SelectedItem != null)
            {
                id = ((TopicInfo)lstInitGrid.SelectedItem).ID;
            }
            GetRecord2(id);
            ShowSecondTab(true);
        }

        private void lstStep_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetStepDetailControl(lstStep.SelectedIndex);
        }

        private void btnLeftArrow_Click(object sender, RoutedEventArgs e)
        {
            //int index = lstStep.SelectedIndex;
            NavigateStep(-1);
        }

        private void btnFirst_Click(object sender, RoutedEventArgs e)
        {
            NavigateStep(-2);
        }


        private void btnLast_Click(object sender, RoutedEventArgs e)
        {
            NavigateStep(9999);
        }


        private void grdRightArrow_Click(object sender, RoutedEventArgs e)
        {
            NavigateStep(1);
        }

        private void stepDetail_Click(object sender, MouseButtonEventArgs e)
        {
            //NavigateStep(1);
        }

        private void imgSound_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (lstStep.SelectedIndex < 0 || lstStep.SelectedItem == null)
            {
                return;
            }

            TopicInfo tInfo = lstStep.SelectedItem as TopicInfo;

            if (App.Current.IsRunningOutOfBrowser && App.Current.HasElevatedPermissions)
            {
                try
                {

                    dynamic textToSpeech = AutomationFactory.CreateObject("Sapi.SpVoice");
                    textToSpeech.Volume = 100;
                    textToSpeech.Speak(tInfo.Help);
                }
                catch (Exception ex)
                {
                    Logging.VLogger.Get().Severe(ex.Message);
                }
            }
            else
            {
                if (String.IsNullOrEmpty(tInfo.Help))
                {
                    return;
                }
                SetBusyStep(true);

                var client = AEnv.GetDataServiceBasicClient();

                client.SpeakCompleted += (o, ea) =>
                {
                    SetBusyStep(false);
                    if (ea.Result != null)
                    {
                        VAdvantage.WavDecoder.WavMediaStreamSource audioStream = new VAdvantage.WavDecoder.WavMediaStreamSource(new MemoryStream(ea.Result));
                        _audioPlayer.SetSource(audioStream);
                    }

                };
                client.SpeakAsync(tInfo.Help);
                client.CloseAsync();
            }
        }

        private void Grid_Loaded_Action(object sender, RoutedEventArgs e)
        {
            helperAction = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)sender,true);
            helperAction.Click += new EventHandler<MouseButtonEventArgs>(helperAction_DoubleClick);
            ((FrameworkElement)sender).Loaded -= Grid_Loaded_Action;
        }

        void helperAction_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            int id = 0;
            if (lstAction.SelectedItem != null)
            {
                TopicInfo t = (TopicInfo)lstAction.SelectedItem;
                StartAction(t.FKID, t.Action);
            }

        }

        private void chk_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox chk = sender as CheckBox;


            tabInitConfig.Visibility = System.Windows.Visibility.Collapsed;
            tabTopic.Visibility = System.Windows.Visibility.Collapsed;
            tabNews.Visibility = System.Windows.Visibility.Collapsed;
            grdSearch.Visibility = System.Windows.Visibility.Visible;

            imgToogle.Visibility = System.Windows.Visibility.Visible;

            if (chk.Name == chkInitConfig.Name)
            {
                tabInitConfig.Visibility = System.Windows.Visibility.Visible;
                chkTopic.IsChecked = false;
                chkNews.IsChecked = false;
            }
            else if (chk.Name == chkTopic.Name)
            {
                tabTopic.Visibility = System.Windows.Visibility.Visible;
                chkInitConfig.IsChecked = false;
                chkNews.IsChecked = false;
            }
            else if (chk.Name == chkNews.Name)
            {
                tabNews.Visibility = System.Windows.Visibility.Visible;
                imgToogle.Visibility = System.Windows.Visibility.Collapsed;
                grdSearch.Visibility = System.Windows.Visibility.Collapsed;
                chkTopic.IsChecked = false;
                chkInitConfig.IsChecked = false;
            }
        }

        private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Cmd_Search();
            }
        }

        private void imgSearch_MouseLeftUp(object sender, MouseButtonEventArgs e)
        {
            Cmd_Search();
        }
       
        #endregion

        private void imgClose_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ShowSecondTab(false);
        }

        private void imgClose1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_parentForm != null)
            {
                _parentForm.Close();
            }
            if (_frame != null)
            {
                _frame.Close();
                
            }
        }


        
    }

    /// <summary>
    /// Topic Class
    /// </summary>
    public class TopicInfo
    {

        public String Name
        {
            get;
            set;
        }

        public String Desc
        {
            get;
            set;
        }

        public String Help
        {
            get;
            set;
        }

        public ImageSource Icon
        {
            get;
            set;
        }

        public int ID
        {
            get;
            set;
        }

        public String Action
        {
            get;
            set;
        }

        public int FKID
        {
            get;
            set;
        }

        public String FKName
        {
            get;
            set;
        }

        public string VID
        {
            get;
            set;
        }
        public string VLength
        {
            get;
            set;
        }

        private object array;

        public TopicInfo(int Id, string name, string desc, string help, object array)
        {
            // TODO: Complete member initialization
            this.Name = name;
            this.Desc = desc;
            this.Help = help;
            this.array = array;
            if (array != null && array is byte[])
            {
                MemoryStream ms = new MemoryStream((byte[])array);
                BitmapSource img = new BitmapImage();
                img.SetSource(ms);
                Icon = img;
            }
            this.ID = Id;

        }
        public TopicInfo(int Id, string name, string desc, string help, object array, string action, int fkID,String fkName,string vid,string length)
        {
            // TODO: Complete member initialization
            this.Name = name;
            this.Desc = desc;
            this.Help = help;
            this.array = array;
            this.VID = vid;
            this.VLength = length;
            if (!string.IsNullOrEmpty(this.VID))
            {
                ;
            }
            else
            if (array != null && array is byte[])
            {
                MemoryStream ms = new MemoryStream((byte[])array);
                BitmapSource img = new BitmapImage();
                img.SetSource(ms);
                Icon = img;
            }
            this.ID = Id;
            this.Action = action;
            this.FKID = fkID;
            this.FKName = fkName;
        }

        public override string ToString()
        {
            return this.Name;
        }
    }
}

